package com.means.polymerize.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author xuhaifeng
 * @date 2019.7.22
 */
@SuppressWarnings("unused")
public class AverageAssignListUtil {

    /**
     * 将一个list均分成n个list,主要通过偏移量来实现的
     *
     * @param source sourceList
     * @return List<List < T>>
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        final List<List<T>> result = new ArrayList<>();
        final AtomicInteger offset = new AtomicInteger();
        final AtomicInteger number = new AtomicInteger(source.size() / n);
        final AtomicInteger remainder = new AtomicInteger(source.size() % n);
        IntStream.range(0, n).forEach(i -> {
            final List<T> value = new ArrayList<>();
            if (remainder.get() > 0) {
                value.addAll(source.subList(i * number.get() + offset.get(), (i + 1) * number.get() + offset.get() + 1));
                remainder.getAndDecrement();
                offset.getAndIncrement();
            } else {
                value.addAll(source.subList(i * number.get() + offset.get(), (i + 1) * number.get() + offset.get()));
            }
            result.add(value);
        });
        return result;
    }

}
